package org.wang.generalcode.modules.sys.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.wang.generalcode.modules.sys.pojo.entity.UserRole;
import org.wang.generalcode.modules.sys.pojo.vo.UserRoleVO;
import org.wang.generalcode.modules.sys.mapper.UserRoleMapper;
import org.wang.generalcode.modules.sys.service.IUserRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户和角色关联表 服务实现类
 *
 * @author wz
 * @since 2024-08-08
 */
@Service
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements IUserRoleService {

	@Override
	public IPage<UserRoleVO> selectUserRolePage(IPage<UserRoleVO> page, UserRoleVO userRole) {
		return page.setRecords(baseMapper.selectUserRolePage(page, userRole));
	}

	@Override
	public boolean saveUserRoles(Long userId, List<Long> roleIds) {
		if (userId == null || CollectionUtil.isEmpty(roleIds)) {
			return false;
		}

		// 用户原角色ID集合
		List<Long> userRoleIds = this.list(new LambdaQueryWrapper<UserRole>()
						.eq(UserRole::getUserId, userId))
				.stream()
				.map(UserRole::getRoleId)
				.collect(Collectors.toList());

		// 新增用户角色
		List<Long> saveRoleIds;
		if (CollectionUtil.isEmpty(userRoleIds)) {
			saveRoleIds = roleIds;
		} else {
			saveRoleIds = roleIds.stream()
					.filter(roleId -> !userRoleIds.contains(roleId))
					.collect(Collectors.toList());
		}

		List<UserRole> saveUserRoles = saveRoleIds
				.stream()
				.map(roleId -> new UserRole(userId, roleId))
				.collect(Collectors.toList());
		this.saveBatch(saveUserRoles);

		// 删除用户角色
		if (CollectionUtil.isNotEmpty(userRoleIds)) {
			List<Long> removeRoleIds = userRoleIds.stream()
					.filter(roleId -> !roleIds.contains(roleId))
					.collect(Collectors.toList());

			if (CollectionUtil.isNotEmpty(removeRoleIds)) {
				this.remove(new LambdaQueryWrapper<UserRole>()
						.eq(UserRole::getUserId, userId)
						.in(UserRole::getRoleId, removeRoleIds)
				);
			}
		}
		return true;
	}

}
